<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>类模式（Class Pattern）</title>
    <!-- 
    在JavaScript中，类模式（Class Pattern）通常指的是使用ES6引入的`class`语法来组织和封装代码。虽然“类模式”并不是一个严格的设计模式，但使用类可以帮助开发者更好地组织代码，实现继承和封装。下面是一些关键点和示例，帮助你理解如何在JavaScript中使用类模式。
    ### 关键点

    1. **封装**：类允许你将数据和操作数据的方法封装在一起。
    2. **继承**：通过`extends`关键字，类可以继承其他类的属性和方法。
    3. **多态**：通过继承和方法重写，可以实现多态性。
    4. **构造函数**：`constructor`方法用于初始化对象。

    ### 示例

    #### 基本类定义

    ```javascript
    class Animal {
        constructor(name) {
            this.name = name;
        }

        speak() {
            console.log(`${this.name} makes a noise.`);
        }
    }

    const animal = new Animal('Generic Animal');
    animal.speak(); // 输出: Generic Animal makes a noise.
    ```

    #### 继承

    ```javascript
    class Dog extends Animal {
        constructor(name, breed) {
            super(name); // 调用父类的构造函数
            this.breed = breed;
        }

        speak() {
            console.log(`${this.name} barks.`);
        }

        fetch() {
            console.log(`${this.name} is fetching the ball.`);
        }
    }

    const dog = new Dog('Buddy', 'Golden Retriever');
    dog.speak(); // 输出: Buddy barks.
    dog.fetch(); // 输出: Buddy is fetching the ball.
    ```

    #### 多态

    ```javascript
    class Cat extends Animal {
        constructor(name, color) {
            super(name);
            this.color = color;
        }

        speak() {
            console.log(`${this.name} meows.`);
        }
    }

    const cat = new Cat('Whiskers', 'Black');
    cat.speak(); // 输出: Whiskers meows.
    ```

    ### 使用类
  --></head>
  <body>
    <script>
      class Animal {
        constructor(name) {
          this.name = name;
        }

        speak() {
          console.log(`${this.name} makes a noise.`);
        }
      }

      const animal = new Animal("Generic Animal");
      animal.speak(); // 输出: Generic Animal makes a noise.

      class Dog extends Animal {
        constructor(name, breed) {
          super(name); // 调用父类的构造函数
          this.breed = breed;
        }

        speak() {
          console.log(`${this.name} barks.`);
        }

        fetch() {
          console.log(`${this.name} is fetching the ball.`);
        }
      }

      const dog = new Dog("Buddy", "Golden Retriever");
      dog.speak(); // 输出: Buddy barks.
      dog.fetch(); // 输出: Buddy is fetching the ball.

      class Cat extends Animal {
        constructor(name, color) {
          super(name);
          this.color = color;
        }

        speak() {
          console.log(`${this.name} meows.`);
        }
      }

      const cat = new Cat("Whiskers", "Black");
      cat.speak(); // 输出: Whiskers meows.
    </script>
  </body>
</html>
